package com.cy.store.service.impl;
import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicatedException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * 用户注册业务层实现类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        //获取结果集并且用findByUsername方法来获取Username
        User username = userMapper.findByUsername(user.getUsername());

        //判断用户是否存在，存在则抛出异常
        if (username != null) {
            throw new UsernameDuplicatedException("用户存在");
        }

        //密码加密MD5
        String oldPassword = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password= getMD5Password(oldPassword,salt);
        //将加密完的密码添加到数据库中
        user.setPassword(md5Password);

        //补全数据库中的字段数据
        user.setIsDelete(0);
        user.setModifiedUser(user.getUsername());
        user.setCreatedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        //执行插入数据操作
        Integer insert = userMapper.insert(user);

        if (insert != 1) {
            throw new InsertException("用户在注册时出现错误");
        }

    }
    private String getMD5Password(String password,String salt){
        for (int i = 1;i<=3;i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;

    }
}

